package com.lemon.springcloud.core.util;

import org.springframework.context.ApplicationContext;

/**
 * Class Name: SpringContextUtils
 * Create Date: 4/27/18 7:19 PM
 * Creator: hdzhang
 * Version: v1.0
 * Updater:
 * Date Time:
 * Description:
 * <p>
 * Provide a method to obtain current spring application context
 */
public final class SpringContextUtils {

    /**
     * saved application context after initialized
     */
    private static ApplicationContext context;

    /**
     * single instance
     */
    private static SpringContextUtils utils = null;

    /**
     * private constructor
     *
     * @param context application context
     */
    private SpringContextUtils(ApplicationContext context) {
        SpringContextUtils.context = context;
    }

    /**
     * initialize current spring application context
     *
     * @param context context
     */
    public static void initInstance(ApplicationContext context) {
        if (context == null) {
            throw new NullPointerException("Application context could not be null.");
        }

        if (utils == null) {
            synchronized (SpringContextUtils.class) {
                if (utils == null) {
                    utils = new SpringContextUtils(context);
                }
            }
        }
    }

    /**
     * Obtain current available application context
     *
     * @return Spring ApplicationContext
     */
    public static ApplicationContext getContext() {
        if (context == null) {
            throw new IllegalStateException("Application context is not ready yet");
        }
        return context;
    }
}
